<template>
  <a-comment
    :author="comment.user?.userName"
    :avatar="comment.user?.userAvatar"
    :content="comment.content"
    :datetime="formattedTime"
  >
    <template #actions>
      <span class="action" key="heart" @click="onLikeChange(comment)">
        <span v-if="comment.liked">
          <IconHeartFill :style="{ color: '#f53f3f' }" />
        </span>
        <span v-else>
          <IconHeart />
        </span>
        {{ comment.likeCount }}
      </span>
      <span class="action" @click="handleReply(comment.id!)">
        <icon-message /> 回复
      </span>
    </template>

    <!-- 子评论 -->
    <div v-if="comment.replies && comment.replies.length > 0">
      <!-- 折叠/展开按钮 -->
      <div
        class="collapse-header"
        @click="toggleCollapse"
        style="cursor: pointer; color: #1890ff; margin-bottom: 8px"
      >
        <span>{{
          collapsed
            ? "展开评论" +
              (comment.replies.length > 0 ? `(${comment.replies.length})` : "")
            : "折叠评论"
        }}</span>
      </div>
      <transition name="collapse">
        <div v-show="!collapsed">
          <CommentItem
            v-for="reply in comment.replies"
            :key="reply.id"
            :comment="reply"
            @reply="handleReply"
            @like="onLikeChange"
            @cencel="cancelReply"
            @loadComment="loadComment"
          />
        </div>
      </transition>
    </div>

    <!-- 回复评论输入框 -->
    <div class="reply-section" v-if="replyTarget.parentId === comment.id">
      <a-textarea
        v-model="replyContent"
        placeholder="输入你的回复..."
        :auto-size="{ minRows: 3 }"
      />
      <div class="action-buttons">
        <a-button type="primary" size="small" @click="submitComment">
          提交
        </a-button>
        <a-button size="small" @click="cancelReply"> 取消 </a-button>
      </div>
    </div>
  </a-comment>
</template>

<script setup lang="ts">
import { ref, computed, reactive, defineProps, defineEmits } from "vue";
import { CommentVO } from "../../generated/models/CommentVO";
import { IconHeart, IconHeartFill } from "@arco-design/web-vue/es/icon";
import { CommentControllerService } from "../../generated/services/CommentControllerService";
import { IconMessage } from "@arco-design/web-vue/es/icon";
import message from "@arco-design/web-vue/es/message";
const components = {
  IconMessage,
};
const props = defineProps<{
  comment: CommentVO;
}>();
import dayjs from "dayjs";
import relativeTime from "dayjs/plugin/relativeTime";
import "dayjs/locale/zh-cn";

dayjs.extend(relativeTime);
dayjs.locale("zh-cn");

/**
 * 将时间戳转换为相对时间描述，例如 "1分钟前"、"1周前"。
 * @param timestamp 形如 2025-02-05T09:13:21.000+00:00 的时间戳
 * @returns 相对时间描述字符串
 */
function formatRelativeTime(timestamp: string): string {
  return dayjs(timestamp).fromNow();
}
const formattedTime = computed(() => {
  return props.comment.createTime
    ? formatRelativeTime(props.comment.createTime)
    : "";
});
// 定义事件
const emit = defineEmits(["reply", "like", "cencel", "loadComment"]);
const replyContent = ref("");
const replyTarget = reactive({
  parentId: null as string | null,
  rootId: null as string | null,
});
const handleReply = (commentId: string) => {
  emit("cencel");
  replyTarget.parentId = commentId;
  emit("reply", commentId);
};
// 当点击点赞时，触发 "like" 事件，通知父组件
const onLikeChange = (comment: CommentVO) => {
  console.log("comment", comment);
  emit("like", comment);
};
const loadComment = () => {
  emit("loadComment");
};
const submitComment = async () => {
  if (!replyContent.value.trim()) return;
  console.log("replyContent", replyContent.value);
  console.log("props.comment", props.comment.id);
  const res = await CommentControllerService.addCommentUsingPost("", {
    commentId: props.comment.id,
    content: replyContent.value,
  });
  if (res.code === 0) {
    emit("loadComment");
    message.success("评论成功");
  } else {
    message.error("评论失败," + res.message);
  }
  cancelReply();
};

const cancelReply = () => {
  emit("cencel");
  replyTarget.parentId = null;
  replyTarget.rootId = null;
  replyContent.value = "";
};

// 新增折叠状态，用于控制嵌套评论的显示与隐藏
const collapsed = ref(false);
const toggleCollapse = () => {
  collapsed.value = !collapsed.value;
};
</script>

<style scoped>
/* 可选：为折叠动画添加简单过渡效果 */
.collapse-enter-active,
.collapse-leave-active {
  transition: all 0.3s ease;
}
.collapse-enter-from,
.collapse-leave-to {
  height: 0;
  opacity: 0;
  overflow: hidden;
}
</style>
